package com.fishery.refrigeratory.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishery.entity.GlobalException;
import com.fishery.entity.Result;
import com.fishery.entity.StatusCode;
import com.fishery.refrigeratory.client.OrderClient;
import com.fishery.refrigeratory.entity.Refrigeratory;
import com.fishery.refrigeratory.entity.RefrigeratoryInInfo;
import com.fishery.refrigeratory.entity.RefrigeratoryOutInfo;
import com.fishery.refrigeratory.entity.vo.OrderAndProductVo;
import com.fishery.refrigeratory.entity.vo.OrderVo;
import com.fishery.refrigeratory.mapper.RefrigeratoryInInfoMapper;
import com.fishery.refrigeratory.mapper.RefrigeratoryMapper;
import com.fishery.refrigeratory.mapper.RefrigeratoryOutInfoMapper;
import com.fishery.refrigeratory.service.RefrigeratoryOutInfoService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RefrigeratoryOutInfoServiceImpl extends ServiceImpl<RefrigeratoryOutInfoMapper, RefrigeratoryOutInfo> implements RefrigeratoryOutInfoService {

    @Autowired
    private RefrigeratoryOutInfoMapper refrigeratoryOutInfoMapper;

    @Autowired
    private RefrigeratoryInInfoMapper refrigeratoryInInfoMapper;

    @Autowired
    private RefrigeratoryMapper refrigeratoryMapper;

    @Autowired
    private OrderClient orderClient;

    /**
     * 根据冷库id查询冷库的出库信息
     * @param refrigeratoryId
     * @return
     */
    @Override
    public List<RefrigeratoryOutInfo> selectInfoBytRefrigeratoryId(String refrigeratoryId) {
        QueryWrapper<RefrigeratoryOutInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("refrigeratory_id", refrigeratoryId);
        return refrigeratoryOutInfoMapper.selectList(wrapper);
    }

    /**
     * 根据冷库id分页查询冷库的出库信息
     * @param refrigeratoryId
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<RefrigeratoryOutInfo> selectPageInfoByRefrigeratoryId(String refrigeratoryId, Integer page, Integer size) {
        QueryWrapper<RefrigeratoryOutInfo> wrapper = new QueryWrapper<RefrigeratoryOutInfo>();
        Page<RefrigeratoryOutInfo> infoPage = new Page<RefrigeratoryOutInfo>(page, size);
        wrapper.eq("refrigeratory_id", refrigeratoryId);
        refrigeratoryOutInfoMapper.selectPage(infoPage, wrapper);
        return infoPage;
    }

    /**
     * 根据基地id查询冷库的出库信息
     * @param refrigeratoryList
     * @return
     */
    @Override
    public List<RefrigeratoryOutInfo> selectInfoByBaseId(List<Refrigeratory> refrigeratoryList) {
        QueryWrapper<RefrigeratoryOutInfo> wrapper = new QueryWrapper<>();
        ArrayList<String> resultList = new ArrayList<>();
        refrigeratoryList.forEach(item->{
            resultList.add(item.getId());
        });
        wrapper.in("refrigeratory_id", resultList);
        return refrigeratoryOutInfoMapper.selectList(wrapper);
    }

    /**
     * 根据基地id分页查询冷库的出库信息
     * @param refrigeratoryList
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<RefrigeratoryOutInfo> selectPageInfoByBaseId(List<Refrigeratory> refrigeratoryList, Integer page, Integer size) {
        QueryWrapper<RefrigeratoryOutInfo> wrapper = new QueryWrapper<>();
        Page<RefrigeratoryOutInfo> infopage = new Page<>(page, size);
        ArrayList<String> resultList = new ArrayList<>();
        refrigeratoryList.forEach(item->{
            resultList.add(item.getId());
        });
        wrapper.in("refrigeratory_id", resultList);
        refrigeratoryOutInfoMapper.selectPage(infopage, wrapper);
        return infopage;
    }

    /**
     * 查询所有出库信息（不限于基地和冷库）
     * @return
     */
    @Override
    public List<RefrigeratoryOutInfo> selectAllInfo() {
        return refrigeratoryOutInfoMapper.selectList(null);
    }

    /**
     * 分页查询所有出库信息（不限于基地和冷库）
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<RefrigeratoryOutInfo> selectPageAllInfo(Integer page, Integer size) {
        Page<RefrigeratoryOutInfo> infoPage = new Page<>(page, size);
        refrigeratoryOutInfoMapper.selectPage(infoPage, null);
        return infoPage;
    }

//    /**
//     * 通过冷库入库编号id查看该编号的出库信息
//     * @param id
//     * @return
//     */
//    @Override
//    public List<RefrigeratoryOutInfo> selectInfoByrefrigeratoryInId(String id) {
//        QueryWrapper<RefrigeratoryOutInfo> wrapper = new QueryWrapper<>();
//        wrapper.eq("refrigeratory_in_id", id);
//        return refrigeratoryOutInfoMapper.selectList(wrapper);
//    }
//
//    /**
//     * 通过冷库出库编号id查看该编号对应的入库编号（溯源）
//     * @param id
//     * @return
//     */
//    @Override
//    public RefrigeratoryOutInfo selectInfoByrefrigeratoryOutId(String id) {
//        return refrigeratoryOutInfoMapper.selectById(id);
//    }
//
//    /**
//     * 通过产品编号id查看冷库出库信息是否存在
//     * @param productId
//     * @return
//     */
//    @Override
//    public RefrigeratoryOutInfo searchRefrigeratoryById(String productId) {
//        return refrigeratoryOutInfoMapper.selectById(productId);
//    }

    /**
     * 修改出库记录
     * @param refrigeratoryOutInfo
     * @return
     */
    @Override
    @Transactional
    public int updateOutInfo(RefrigeratoryOutInfo refrigeratoryOutInfo) {
        if (refrigeratoryOutInfo.getRefrigeratoryOutCapacity() <= 0) {
            throw new GlobalException(StatusCode.ERROR, "请输入数据, 并且保证修改容量的值大于0");
        }
        //得到原来的入库信息
        RefrigeratoryInInfo InRefrigeratory = refrigeratoryInInfoMapper.selectById(refrigeratoryOutInfo.getRefrigeratoryInId());
        if (InRefrigeratory == null) {
            throw new GlobalException(StatusCode.ERROR, "找不到该出库信息对应的入库信息");
        }
        //得到之前的出库记录
        RefrigeratoryOutInfo beforerefrigeratory = refrigeratoryOutInfoMapper.selectById(refrigeratoryOutInfo.getId());
        if (beforerefrigeratory == null) {
            throw new GlobalException(StatusCode.ERROR, "未找到对应出库信息");
        }
        //得到冷库的已用容量,如果冷库不存在则退出
        Refrigeratory refrigeratory = refrigeratoryMapper.selectById(beforerefrigeratory.getRefrigeratoryId());
        if (refrigeratory == null) {
            throw new GlobalException(StatusCode.ERROR, "找不到该出库信息对应的冷库");
        }

        //得到修改容量
        double updateCapacity = refrigeratoryOutInfo.getRefrigeratoryOutCapacity();
        //原始出库容量
        double beforeOutCapacity = beforerefrigeratory.getRefrigeratoryOutCapacity();

        //如果修改前和修改后的容量一致，那就是没有修改容量
        if (updateCapacity == beforeOutCapacity) {
            return refrigeratoryOutInfoMapper.updateById(refrigeratoryOutInfo);
        } else {
            //得到冷库已用容量
            double AllUsedCapacity = refrigeratory.getRefrigeratoryUsedCapacity();
            //得到修改前对应信息的入库的已消耗（出库）容量
            double InUsedCapacity = InRefrigeratory.getRefrigeratoryInUsedCapacity();
            //得到修改前对应信息的入库的总容量
            double AllInCapacity = InRefrigeratory.getRefrigeratoryInCapacity();
            //可以修改容量的最大值
            double max = AllInCapacity - InUsedCapacity + beforeOutCapacity;
            if (updateCapacity > max) {
                throw new GlobalException(StatusCode.ERROR, "修改失败, 修改的容量过大，请控制修改后的容量在" + max + "kg之内");
            }
            refrigeratory.setRefrigeratoryUsedCapacity(AllUsedCapacity - (updateCapacity - beforeOutCapacity));
            InRefrigeratory.setRefrigeratoryInUsedCapacity(InUsedCapacity - (beforeOutCapacity - updateCapacity));
        }
        refrigeratoryMapper.updateById(refrigeratory);
        refrigeratoryInInfoMapper.updateById(InRefrigeratory);
        return refrigeratoryOutInfoMapper.updateById(refrigeratoryOutInfo);
    }

    /**
     * 创建出库记录
     * @param refrigeratoryOutInfo
     * @return
     */
    @Override
    @Transactional
    public int insertOutInfo(RefrigeratoryOutInfo refrigeratoryOutInfo) {
        //得到入库信息
        RefrigeratoryInInfo InRefrigeratory = refrigeratoryInInfoMapper.selectById(refrigeratoryOutInfo.getRefrigeratoryInId());
        if (InRefrigeratory == null) {
            throw new GlobalException(StatusCode.ERROR, "找不到该出库信息对应的入库信息！");
        }
        //如果冷库不存在则退出
        Refrigeratory refrigeratory = refrigeratoryMapper.selectById(InRefrigeratory.getRefrigeratoryId());
        if (refrigeratory == null) {
            throw new GlobalException(StatusCode.ERROR, "找不到该出库信息对应的冷库");
        }
        //获得当前冷库已用容量
        double AllUsedCapacity = refrigeratory.getRefrigeratoryUsedCapacity();
        //当前输出容量
        double OutCapacity = refrigeratoryOutInfo.getRefrigeratoryOutCapacity();
        //得到当前入库信息总容量
        double InCapacity = InRefrigeratory.getRefrigeratoryInCapacity();
        //得到当前入库信息已使用容量
        double InUsedCapacity = InRefrigeratory.getRefrigeratoryInUsedCapacity();
        //剩余容量
        double surplus = InCapacity - InUsedCapacity;
        if (InUsedCapacity + OutCapacity > InCapacity) {
            throw new GlobalException(StatusCode.ERROR, "新增出库信息失败！！！当前容量不足，只剩余"+ surplus + "kg的容量");
        }
        InRefrigeratory.setRefrigeratoryInUsedCapacity(InUsedCapacity + OutCapacity);
        refrigeratory.setRefrigeratoryUsedCapacity(AllUsedCapacity - OutCapacity);
        refrigeratoryMapper.updateById(refrigeratory);
        refrigeratoryInInfoMapper.updateById(InRefrigeratory);
        refrigeratoryOutInfo.setProductName(InRefrigeratory.getProductName());
        refrigeratoryOutInfo.setRefrigeratoryProductId(InRefrigeratory.getProcessingBaseId());
        refrigeratoryOutInfo.setRefrigeratoryId(InRefrigeratory.getRefrigeratoryId());
        return refrigeratoryOutInfoMapper.insert(refrigeratoryOutInfo);
    }

    /**
     *删除出库记录
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int deleteOutIno(String id) {
        //删除了之后对应的已用容量要删除,如果入库信息不存在则退出
        RefrigeratoryOutInfo refrigeratoryOutInfo = refrigeratoryOutInfoMapper.selectById(id);
        if (refrigeratoryOutInfo == null) {
            throw new GlobalException(StatusCode.ERROR, "找不到该id对应的出库记录！");
        }
        //得到入库信息
        RefrigeratoryInInfo InRefrigeratory = refrigeratoryInInfoMapper.selectById(refrigeratoryOutInfo.getRefrigeratoryInId());
        if (InRefrigeratory == null) {
            throw new GlobalException(StatusCode.ERROR, "找不到该出库信息对应的入库信息！");
        }
        Refrigeratory refrigeratory = refrigeratoryMapper.selectById(refrigeratoryOutInfo.getRefrigeratoryId());
        if (refrigeratory == null) {
            throw new GlobalException(StatusCode.ERROR, "找不到该出库信息对应的冷库信息！");
        }
        //得到冷库已用容量
        double AllUsedCapacity = refrigeratory.getRefrigeratoryUsedCapacity();
        //得到当前出库信息的出库容量
        double OutCapacity = refrigeratoryOutInfo.getRefrigeratoryOutCapacity();
        //剩余容量
        InRefrigeratory.setRefrigeratoryInUsedCapacity(InRefrigeratory.getRefrigeratoryInUsedCapacity() - OutCapacity);
        refrigeratory.setRefrigeratoryUsedCapacity(AllUsedCapacity + OutCapacity);
        refrigeratoryMapper.updateById(refrigeratory);
        refrigeratoryInInfoMapper.updateById(InRefrigeratory);
        return refrigeratoryOutInfoMapper.deleteById(id);
    }

//    /**
//     * 创建订单
//     * @param orderAndProductVo
//     */
//    @Override
//    public Boolean createOrder(OrderAndProductVo orderAndProductVo) {
////        //创建出库记录
////        RefrigeratoryOutInfo outInfo  = new RefrigeratoryOutInfo();
////        outInfo.setRefrigeratoryInId(orderAndProductVo.getRefrigeratoryInId());
////        outInfo.setRefrigeratoryOutDescription(orderAndProductVo.getRefrigeratoryOutDescription());
////        outInfo.setRefrigeratoryOutCapacity((int)(orderAndProductVo.getAmount() * orderAndProductVo.getWeight()));
////        outInfo.setWarehousingPersonId(orderAndProductVo.getWarehousingPersonId());
////        outInfo.setRefrigeratoryOutTime(new Date());
////        int insert = refrigeratoryOutInfoMapper.insert(outInfo);
////        if (insert == 0) {
////            return false;
////        }
//        //创建订单
//        OrderVo orderVo = new OrderVo();
//        orderVo.setTargetId(orderAndProductVo.getTargetId());
//        orderVo.setTargetName(orderAndProductVo.getTargetName());
//        orderVo.setProductName(orderAndProductVo.getProductName());
//        orderVo.setProductId(IdWorker.getIdStr());
//        orderVo.setBaseId(orderAndProductVo.getBaseId());
//        orderVo.setWeight(orderAndProductVo.getWeight());
//        orderVo.setReceiveAddress(orderAndProductVo.getReceiveAddress());
//        orderVo.setAddressLongitude(orderAndProductVo.getAddressLongitude());
//        orderVo.setAddressLatitude(orderAndProductVo.getAddressLatitude());
//        orderVo.setPhoneNumber(orderAndProductVo.getPhoneNumber());
//        orderVo.setMoney(orderAndProductVo.getMoney());
//        orderVo.setAmount(orderAndProductVo.getAmount());
//        orderVo.setSourceType(3);
//        orderVo.setStatus(0);
//        orderVo.setTargetType(orderAndProductVo.getTargetType());
//        Result order = orderClient.createOrder(orderVo);
//        if (order.getStatusCode() != 20000) {
//            throw new GlobalException(StatusCode.ERROR, "创建订单失败");
//        }
//        return true;
//    }
//
//    /**
//     * 创建订单自动调用库存
//     * @param orderVo
//     * @return
//     */
//    @Override
//    public Boolean createOutInfo(OrderVo orderVo) {
//        //创建出库记录
//        RefrigeratoryOutInfo outInfo  = new RefrigeratoryOutInfo();
//        outInfo.setRefrigeratoryOutCapacity((int)(orderVo.getAmount() * orderVo.getWeight()));
//        outInfo.setRefrigeratoryOutTime(new Date());
//        int insert = refrigeratoryOutInfoMapper.insert(outInfo);
//        return insert == 0;
//    }

}
